package generic

import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"webDownloader/engine/base"
)

type EngineGeneric struct {
	// 命令行配置
	Conf  map[string]interface{}
	Tasks []base.IDownload
}

func (e *EngineGeneric) Accept(url string) bool {
	//fmt.Println("免费功能，权限校验无条件通过")
	return false
}

func (e *EngineGeneric) Auth() bool {
	//fmt.Println("免费功能，权限校验无条件通过")
	return true
}

func (e *EngineGeneric) ParseConfig() *map[string]interface{} {
	fmt.Println("正在解析命令行配置...")
	await := flag.Bool("await", false, "在下载完毕后不自动退出，直到手动关闭窗口或杀死进程")
	fileName := flag.String("name", "index.html", "文件名")
	hideDonate := flag.Bool("d", false, "在下载完成后不显示捐助信息，直接退出")
	flag.Parse()
	e.Conf["await"] = *await
	e.Conf["fileName"] = *fileName
	e.Conf["hideDonate"] = *hideDonate
	return &e.Conf
}

func (e *EngineGeneric) SetConfig(conf map[string]interface{}) {
	e.Conf = conf
}

func (e *EngineGeneric) GetConfig() *map[string]interface{} {
	return &e.Conf
}

func (e *EngineGeneric) ParseDownloadTask() []base.IDownload {
	e.Tasks = make([]base.IDownload, 0)
	if e.Conf["refUrl"] != nil {
		_url := e.Conf["refUrl"].(string)
		fileName := e.Conf["fileName"].(string)
		e.Tasks = append(e.Tasks, &DownloadTaskGeneric{
			DownloadTask: base.DownloadTask{
				Url:      _url,
				FileName: fileName,
			},
			Context: e,
		})
	}
	return e.Tasks
}

func (e *EngineGeneric) SyncDownloadTask() []base.IDownload {
	// 对下载任务进行同步（去掉已完成的任务），在通用下载器中不做处理
	return e.Tasks
}

func (e *EngineGeneric) ShowEndMessage() {
	fmt.Println("下载完毕")
	if !e.Conf["hideDonate"].(bool) {
		fmt.Println("\n如果这个软件帮到了您，不妨【按回车键】打开作者的捐助链接,扫码捐助，您的支持是我持续改进软件的动力！\n如果您不希望看到此消息，请在命令行用 -d 屏蔽或直接关闭窗口。")
		reader := bufio.NewReader(os.Stdin)
		reader.ReadRune()
		switch runtime.GOOS {
		case "windows":
			exec.Command(`cmd`, `/c`, `start`, `https://kbtxwer.gitee.io/wxac_donate.jpg`).Start()
		case "linux":
			exec.Command(`xdg-open`, `https://kbtxwer.gitee.io/wxac_donate.jpg`).Start()
		case "mac":
			exec.Command(`open`, `https://kbtxwer.gitee.io/wxac_donate.jpg`).Start()
		}
	}
}
